package com.lee.www.controller;

import com.lee.www.Mapper.RoleMapper;
import com.lee.www.Mapper.UserMapper;
import com.lee.www.entity.Role;
import com.lee.www.entity.User;
import com.lee.www.vo.CommonResult;
import com.lee.www.vo.MsgInfo;
import com.lee.www.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @GetMapping("/list")
    public List<User> list() {
        return userMapper.selectList(null);
    }

    @PostMapping()
    public void insert(User user) {
        userMapper.insert(user);
    }

    @GetMapping("/vo/list")
    public CommonResult voList() {
        List<User> users = userMapper.selectList(null);
        List<UserVo> userVos = new ArrayList<>();
        for (User user : users) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            Role role = roleMapper.selectById(user.getRoleId());
            BeanUtils.copyProperties(role, userVo);
            userVos.add(userVo);
        }
        MsgInfo msgInfo = MsgInfo.initMsgInfo(200L, "查询成功");
        return CommonResult.initCommonResult(userVos, msgInfo);
    }
}
